package com.innotek.testworkstation.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName CachePool
 * @Description 本地MAP缓存,Map<String, Object>
 * @Author wangx
 * @Date 2021/8/6 下午1:59
 * @Version 1.0
 **/


public class CachePool {
    private static CachePool cachePool;
    private Map<String, Object> cacheItems;
    private CachePool() {
        cacheItems =new ConcurrentHashMap<String, Object>();
    }
    /**
     * 获取唯一实例
     * @return instance
     */
    public static CachePool getInstance() {
        if (cachePool ==null) {
            synchronized (CachePool.class) {
                if (cachePool ==null) {
                    cachePool =new CachePool();
                }
            }
        }
        return cachePool;
    }

    /**
     * 获取所有cache信息
     * @return cacheItems
     */
    public Map<String, Object> getCacheItems() {
        return this.cacheItems;
    }

    /**
     * 清空cache
     */
    public void clearAllItems() {
        cacheItems.clear();
    }

    /**
     * 获取指定cache信息
     * @return cacheItem
     */
    public Object getCacheItem(String key) {
        if (cacheItems.containsKey(key)) {
            return cacheItems.get(key);
        }
        return null;
    }

    /**
     * 获取指定cache信息(String格式)
     * @return cacheItem
     */
    public String getStringCacheItem(String key) {
        if (cacheItems.containsKey(key)) {
            return String.valueOf(cacheItems.get(key));
        }
        return null;
    }

    /**
     * 存放cache信息
     */
    public void putCacheItem(String key,Object value) {
//        if (!cacheItems.containsKey(key)) {
//            cacheItems.put(key, value);
//        }
        cacheItems.put(key, value);
    }

    /**
     * 存放cache信息
     */
    public void putCacheAllItem(Map<String, Object> map) {
//        if (!cacheItems.containsKey(key)) {
//            cacheItems.put(key, value);
//        }
        cacheItems.putAll(map);
    }

    /**
     * 删除一个cache
     */
    public void removeCacheItem(String key) {
        cacheItems.remove(key);
    }

    /**
     * 获取cache长度
     * @return size
     */
    public int getSize() {
        return cacheItems.size();
    }

}